﻿using Microsoft.Xaml.Behaviors;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace _1_行为
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }

    class MyBehavior : Behavior<Border>
    {
        protected override void OnAttached()
        {
            AssociatedObject.Background = Brushes.Blue;
        }
    }

    class ClearTextBehavior : Behavior<Button>
    {


        public TextBox Target
        {
            get { return (TextBox)GetValue(TargetProperty); }
            set { SetValue(TargetProperty, value); }
        }

        public static readonly DependencyProperty TargetProperty =
            DependencyProperty.Register("Target", typeof(TextBox), typeof(ClearTextBehavior), new PropertyMetadata(null));

        protected override void OnAttached()
        {
            AssociatedObject.Click += ButtonClick;
        }

        private void ButtonClick(object sender, RoutedEventArgs e)
        {
            Target?.Clear();
        }

        protected override void OnDetaching()
        {
            AssociatedObject.Click -= ButtonClick;
        }
    }

    class MouseWheelBehavior : Behavior<TextBox>
    {
        public int MaxValue { get; set; } = int.MaxValue;
        public int MinValue { get; set; } = int.MinValue;
        public int Scale { get; set; } = 1;

        protected override void OnAttached()
        {
            AssociatedObject.MouseWheel += MouseWheel;
        }

        protected override void OnDetaching()
        {
            AssociatedObject.MouseWheel -= MouseWheel;
        }

        private void MouseWheel(object sender, MouseWheelEventArgs e)
        {
            var value = int.Parse(AssociatedObject.Text);
            if (e.Delta > 0)
            {
                value += Scale;
                if (value > MaxValue) value = MaxValue;
            }
            else
            {
                value -= Scale;
                if (value < MinValue) value = MinValue;
            }

            AssociatedObject.Text = value.ToString();
        }

    }
}
